<?php
declare ( strict_types = 1 );

namespace app;
use app\BaseController;
use app\card\model\User;
use app\card\model\UserPhone;
use app\restaurant\model\Table;
use longbingcore\tools\LongbingArr;
use Qiniu\Auth;
use think\App;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Request;
use think\Validate;
use think\Response;
use think\facade\Db;
use think\facade\Lang;
/**
 * 控制器基础类
 */
abstract class ApiRest extends BaseController
{
    //app名称
    public $_app = null;
    //控制器名称
    public $_controller = null;
    //执行方法名称
    public $_action = null;
    //method
    public $_method = 'GET';
    //query参数
    public $_param = [];
    //body参数
    public $_input = [];
    //头部
    public $_header = [];
    //头部token
    public $_token = null;
    //语言信息
    public $_lang = 'zh-cn';
    //角色
    public $_role = 'guest';
    //host信息
    public $_host = null;
    //访问ip信息
    public $_ip = null;
    //用户信息
    public $_user = null;
    //获取用户id
    public $_user_id = null;
    //唯一app标示
    public $_uniacid = 2;
    //是否是抖音
    public $isdouyin = 0;
    //定义检查中间件
    protected $middleware = [ 'app\middleware\CheckInput' ,'think\middleware\LoadLangPack'  ,'app\middleware\GetAuthConfig' ,'app\middleware\AutoStatic','app\middleware\StaticHour'];

    //获取配置信息
    protected $_config = [];

    //  小程序登陆每个用户产生的唯一表示
    protected $autograph = '';

    protected $uniacid = 0;

    protected $defaultImage = array(
        //  默认用户头像
        'avatar' => 'https://lbqnyv2.migugu.com/defaultAvatar.png',
        //  默认内容图片
        'image' => 'https://lbqnyv2.migugu.com/lbCardDefaultImage.png',
    );

    protected $_is_weiqin = false ;

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];


    public function __construct ( App $app )
    {
        parent::__construct( $app );

        if ( defined( 'IS_WEIQIN' ) ) {
            global $_GPC, $_W;
            $this->_uniacid = $_W[ 'uniacid' ];
            $this->_is_weiqin = true ;
        }

        if(in_array($this->_method,['options','Options','OPTIONS'])){

            echo true;exit;
        }
        //获取param
        $this->_param = $this->request->param();
        //获取body参数

        if(longbing_get_app_type()=='baiduboxapp'){

            $input = $this->request->getInput();

            $type = longbing_get_mobile_type();

            if($type == 'iPhone'){
                parse_str($input , $inputArr) ;

                $this->_input  = $inputArr ;
            }else{
                $this->_input = json_decode( $input, true );
            }

        }else{
            $this->_input = json_decode( $this->request->getInput(), true );
        }
        //获取头部信息
        $this->_header  = $this->request->header();

        $this->isdouyin = !empty($this->_header['isdouyin'])?1:0;

        if ( defined( 'IS_WEIQIN' ) )
        {
            global $_GPC, $_W;
            $this->_uniacid = $_W[ 'uniacid' ];
        }
        else
        {
            if(isset($this->_param[ 'i' ]))
            {
                $this->_uniacid = $this->_param[ 'i' ];
            }

        }

        if ( defined( 'LONGBING_CARD_UNIACID' ) )
        {

            define( 'LONGBING_CARD_UNIACID', $this->_uniacid );
        }

        $this->shareChangeData($this->_param);

        if(!$this->match($this->noNeedLogin)){
            //获取autograph 小程序用户唯一标示
            if ( isset( $this->_header[ 'autograph' ] ) && $this->_header[ 'autograph' ])
            {
                $this->autograph = $this->_header['autograph'];
            }
            else
            {

                $this->errorMsg('need login',401);
            }
        }

//获取配置信息
        $this->_config = longbingGetAppConfig($this->_uniacid);

        //获取token
        //  if ( isset( $this->_header[ 'token' ] ) ) $this->_token = $this->_header[ 'token' ];
        //语言
        if ( isset( $this->_header[ 'lang' ] ) ) $this->_token = $this->_header[ 'lang' ];
        //获取请求host
        // $this->_host = $this->_header[ 'host' ];
        //获取访问ip
        // $this->_ip = $_SERVER[ 'REMOTE_ADDR' ];
        // 控制器初始化
        $this->initialize();

        if(!empty($this->autograph)&&!$this->match($this->noNeedLogin)){

            $this->_user_id = $this->getUserId();

            $this->_user    = $this->getUserInfo();
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-21 17:43
     * @功能说明:
     */
    public function shareChangeData($input){

        $arr = [

            'shop/IndexShopGoods/goodsInfo',

            'im/app/getCustomerUnReadMessageCount',

            'decorate/IndexCase/caseInfo',

            '/diy/app/getDiyData',

            'decorate/IndexSite/siteList',

            'house/app/IndexAppHouse/longPageInfo',

            'shop/IndexShopGoods/getGoodsParameter',

            'decorate/IndexCase/configInfo',

        ];

        if(!empty($input['timeline'])&&$input['timeline']==1&&!empty($input['s'])&&in_array($input['s'],$arr)){

            $input['s'] =  trim(strrchr($input['s'], '/'),'/');

            $this->noNeedLogin[] = $input['s'];
        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-07-09 12:00
     * @功能说明:检测方法传递
     */
    public function match($arr){


        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr)
        {
            return FALSE;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($this->request->action()), $arr) || in_array('*', $arr))
        {
            return TRUE;
        }

        // 没找到匹配
        return FALSE;
    }

    //返回请求成功的数据
    public function success ( $data, $code = 200 )
    {
        $result[ 'data' ] = LongbingGetWxApiReturnData($data);
        $result[ 'code' ] = $code;
        $result[ 'sign' ] = null;
        //复杂的签名
        //		if(isset($this->_user['keys'])){
        //			$result['sign'] = rsa2CreateSign($this->_user['keys'] ,json_encode($data));
        //		}
        //简单的签名
        if ( !empty( $this->_token ) ) $result[ 'sign' ] = createSimpleSign( $this->_token, is_string( $data ) ? $data : json_encode( $data ) );
        return $this->response( $result, 'json', $code  );
    }

    //返回错误数据
    public function error ( $msg, $code = 400 )
    {
//      $result[ 'error' ] = Lang::get($msg);
//      $result[ 'code' ]  = $code;
        $result = $this->getErrorData($msg, $code);
        return $this->response( $result, 'json', 200 );
    }

    public function getErrorData($msg, $code = 400)
    {
        $result[ 'error' ] = Lang::get($msg);
        $result[ 'code' ]  = $code;
        return $result;
    }
    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态码
     * @return Response
     */
    protected function response ( $data, $type = 'json', $code = 200 )
    {
        return Response::create( $data, $type )->code( $code );
    }

    /**
     * REST 调用
     * @access public
     * @param string $method 方法名
     * @return mixed
     * @throws \Exception
     */
    public function _empty ( $method )
    {
        if ( method_exists( $this, $method . '_' . $this->method . '_' . $this->type ) )
        {
            // RESTFul方法支持
            $fun = $method . '_' . $this->method . '_' . $this->type;
        }
        elseif ( $this->method == $this->restDefaultMethod && method_exists( $this, $method . '_' . $this->type ) )
        {
            $fun = $method . '_' . $this->type;
        }
        elseif ( $this->type == $this->restDefaultType && method_exists( $this, $method . '_' . $this->method ) )
        {
            $fun = $method . '_' . $this->method;
        }
        if ( isset( $fun ) )
        {
            return App::invokeMethod( [ $this, $fun ]
            );
        }
        else
        {
            // 抛出异常
            throw new \Exception( 'error action :' . $method );
        }
    }

    /**
     * @Purpose: 通过小程序端的用户标示获取用户信息
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function getUserInfo ()
    {
        $value = getCache( $this->autograph, $this->_uniacid );

        if ( $value === false&&!$this->match($this->noNeedLogin) )
        {
            echo json_encode( [ 'code' => 401, 'error' => 'need login!' ] );
            exit;
            $user_id = $this->getUserId();

            if ( $user_id === false )
            {
                echo json_encode( [ 'code' => 401, 'error' => 'need login!' ] );
                exit;
            }

            $value = User::where( [ 'id', '=', $user_id ]
            )
                ->find();

            $phone           = UserPhone::where( [ [ 'user_id', '=', $user_id ] ]
            )
                ->find();

            $value[ 'phone' ] = $phone ? $phone[ 'phone' ] : '';

            $value = handleImagesWe7Local( $value, [ 'qr_path', 'pay_qr' ], ','
            );
        }

        $store = Db::name('longbing_card_user')->where(['id'=>$value['id']])->field('store_id,table_id')->find();

        $value['store_id'] = $store['store_id'];

        $table_model       = new Table();
        //检查一下桌号
        $value['table_id'] = $table_model->checkStoreTable($value['store_id'],$store['table_id']);

        return $value;
    }

    /**
     * @Purpose: 通过小程序端的用户标示获取用户id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function getUserId ()
    {


        $value = getCache( $this->autograph, $this->_uniacid );

        if ( $value === false &&!$this->match($this->noNeedLogin))
        {

            $this->errorMsg('need login',401);
//            echo json_encode( [ 'code' => 401, 'error' => 'need login!!' ] );
//            exit;

        }
//        dump($value);exit;
        return $value[ 'id' ];
    }
    /**
     *
     * 获取支付信息
     */
    public function payConfig ($uniacid = ''){
        $uniacid_id = !empty($uniacid)?$uniacid:$this->_uniacid;
        $pay    = Db::name('longbing_card_config_pay')->where(['uniacid'=>$uniacid_id])->find();
        $config = Db::name( 'longbing_card_config')->where(['uniacid' => $uniacid_id])->find();
        if(empty($pay[ 'mch_id' ])||empty($pay[ 'pay_key' ])){
            $this->errorMsg('未配置支付信息');
        }
        $setting[ 'payment' ][ 'merchant_id' ] = $pay[ 'mch_id' ];
        $setting[ 'payment' ][ 'key' ]         = $pay[ 'pay_key' ];
        $setting[ 'payment' ][ 'cert_path' ]   = $pay[ 'cert_path' ];
        $setting[ 'payment' ][ 'key_path' ]    = $pay[ 'key_path' ];
        $setting[ 'app_id' ]                   = $config['appid'];
        $setting[ 'secret' ]                   = $config['app_secret'];
        return $setting;
    }

    /**
     * @Purpose: 获取formId
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */

    public function getFormId ( $to_uid )
    {
        return [];
        // 七天前开始的的时间戳
        // $beginTime = mktime( 0, 0, 0, date( 'm' ), date( 'd' ) - 6, date( 'Y' ) );
        $beginTime = strtotime(date('Y-m-d',time()))-86400*6;
        $formId    = Db::name( 'longbing_card_formId' )
            ->where( [ 'user_id' => $to_uid ] )
            ->order( 'id desc' )
            ->select();
        if ( empty( $formId ) )
        {
            return false;
        }
        if ( $formId[ 0 ][ 'create_time' ] < $beginTime )
        {
            Db::name( 'longbing_card_formId' )
                ->where( [ 'id' => $formId[ 0 ][ 'id' ] ] )
                ->delete();
            $this->getFormId( $to_uid );
        }
        else
        {
            Db::name( 'longbing_card_formId' )
                ->where( [ 'id' => $formId[ 0 ][ 'id' ] ] )
                ->delete();
            return $formId[ 0 ][ 'formId' ];
        }
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 20:37
     * @param string $msg
     * @return void
     * descption:直接抛出异常
     */
    protected function errorMsg($msg = '',$code = 400){
        $msg = Lang::get($msg);
        $this->results($msg,$code);
    }

    /**
     * User: chenniang
     * Date: 2019-09-12 20:42
     * @param $msg
     * @param int $code
     * @param array $header
     * @return void
     * descption:直接抛出状态
     */
    protected function results($msg, $code, array $header = [])
    {
        $result = [
            'error' => $msg,
            'code'  => $code,
        ];
        $response = Response::create($result, 'json', 200)->header($header);
        throw new HttpResponseException($response);
    }
}
